package com.wg.dome;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.wg.core.net.OperationRequest;
import com.wg.core.net.OperationResponse;
import com.wg.core.net.SendParameters;
import com.wg.dome.handle.BaseHandle;
import com.wg.net.*;
import com.wg.net.operations.InitRequest;

public class ClientPeer extends BasePeer {
    private static final Log log = LogFactory.get();
    private final DomeApplication application;
    private long playerId;


    public ClientPeer(InitRequest initRequest, DomeApplication application) {
        super(initRequest);
        this.application = application;
    }

    public void setPlayerId(long playerId) {
        this.playerId = playerId;
    }

    public long getPlayerId() {
        return playerId;
    }

    public DomeApplication getApplication() {
        return application;
    }

    @Override
    protected void onDisconnect(DisconnectReason reasonCode, String reasonDetail) {
        log.info("onDisconnect:{}", this.getConnectionId());
        application.getChatLobby().onRemoveAllChannel(this);
    }

    @Override
    protected void onOperationRequest(OperationRequest request, SendParameters sendParameters) {
        final long startExecTime = System.nanoTime();

        OperationResponse response = null;
        try {
            String handleName = StrUtil.format("com.wg.dome.handle.HandleRequest{}", request.getOperationCode());
            Class<?> clazz = Class.forName(handleName);
            BaseHandle handle = (BaseHandle) ReflectUtil.newInstance(clazz);
            response = handle.execute(this, request, sendParameters);
        } catch (Exception e) {
            if (e instanceof  ClassNotFoundException){
                response = new OperationResponse(request.getOperationCode());
                response.setDebugMessage(ErrorCode.OPERATION_UNKNOWN.getMsg());
                response.setReturnCode(ErrorCode.OPERATION_UNKNOWN.getCode());
            }
            else{
                e.printStackTrace();
                response = ErrorHelper.getErrorResponse(request.getOperationCode(), ErrorCode.INNER_ERROR);
            }
        } finally {
            if (response != null) {
                sendOperationResponse(response, sendParameters);
                if (response.getReturnCode() != 0) {
                    log.error("handle request({}), errorcode={} errdbsg={}",
                            request.getOperationCode(), response.getReturnCode(), response.getDebugMessage());
                }
            }
            final long endExecuteTime = System.nanoTime();
            log.info("handle request({}), exe={} ms", request.getOperationCode(), (endExecuteTime - startExecTime) / 100_0000F);
        }
    }
}
